/**
 * 用户引导状态管理
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useGuideStore = defineStore('guide', () => {
  // 状态
  const isGuideActive = ref(false)
  const currentStep = ref(0)
  const guideCompleted = ref(false)
  const userPreferences = ref({
    showWelcomeMessage: true,
    autoStartGuide: true,
    skipAnimations: false
  })

  // 引导步骤数据
  const guideSteps = ref([
    {
      id: 'welcome',
      title: '欢迎使用心理健康助手',
      description: '我是您的专业心理健康伙伴，提供24小时贴心陪伴和专业建议。',
      type: 'welcome',
      required: true
    },
    {
      id: 'chat-interface',
      title: '对话界面介绍',
      description: '了解如何与AI助手进行有效对话',
      type: 'feature',
      required: true
    },
    {
      id: 'privacy-security',
      title: '隐私与安全',
      description: '了解我们如何保护您的隐私和数据安全',
      type: 'info',
      required: true
    },
    {
      id: 'first-conversation',
      title: '开始第一次对话',
      description: '让我们开始您的第一次心理健康对话',
      type: 'interactive',
      required: true
    }
  ])

  // 计算属性
  const totalSteps = computed(() => guideSteps.value.length)
  const progress = computed(() => {
    if (totalSteps.value === 0) return 0
    return Math.round((currentStep.value / totalSteps.value) * 100)
  })
  
  const currentStepData = computed(() => {
    return guideSteps.value[currentStep.value] || null
  })

  const isFirstTime = computed(() => {
    return !localStorage.getItem('user-guide-completed')
  })

  // 方法
  const startGuide = () => {
    console.log('🎯 [GuideStore] 开始用户引导')
    isGuideActive.value = true
    currentStep.value = 0
    guideCompleted.value = false
  }

  const nextStep = () => {
    if (currentStep.value < totalSteps.value - 1) {
      currentStep.value++
      console.log(`📍 [GuideStore] 进入步骤 ${currentStep.value + 1}/${totalSteps.value}`)
    } else {
      completeGuide()
    }
  }

  const previousStep = () => {
    if (currentStep.value > 0) {
      currentStep.value--
      console.log(`📍 [GuideStore] 返回步骤 ${currentStep.value + 1}/${totalSteps.value}`)
    }
  }

  const goToStep = (stepIndex) => {
    if (stepIndex >= 0 && stepIndex < totalSteps.value) {
      currentStep.value = stepIndex
      console.log(`📍 [GuideStore] 跳转到步骤 ${stepIndex + 1}/${totalSteps.value}`)
    }
  }

  const completeGuide = () => {
    console.log('✅ [GuideStore] 用户引导完成')
    isGuideActive.value = false
    guideCompleted.value = true
    
    // 保存完成状态
    localStorage.setItem('user-guide-completed', 'true')
    localStorage.setItem('user-guide-completed-date', new Date().toISOString())
    
    // 保存用户偏好
    saveUserPreferences()
  }

  const skipGuide = () => {
    console.log('⏭️ [GuideStore] 用户跳过引导')
    isGuideActive.value = false
    guideCompleted.value = true
    
    // 标记为跳过
    localStorage.setItem('user-guide-completed', 'true')
    localStorage.setItem('user-guide-skipped', 'true')
    localStorage.setItem('user-guide-completed-date', new Date().toISOString())
  }

  const resetGuide = () => {
    console.log('🔄 [GuideStore] 重置用户引导')
    isGuideActive.value = false
    currentStep.value = 0
    guideCompleted.value = false
    
    // 清除本地存储
    localStorage.removeItem('user-guide-completed')
    localStorage.removeItem('user-guide-skipped')
    localStorage.removeItem('user-guide-completed-date')
    localStorage.removeItem('user-guide-preferences')
  }

  const loadUserPreferences = () => {
    try {
      const saved = localStorage.getItem('user-guide-preferences')
      if (saved) {
        const preferences = JSON.parse(saved)
        userPreferences.value = { ...userPreferences.value, ...preferences }
        console.log('📋 [GuideStore] 用户偏好已加载', userPreferences.value)
      }
    } catch (error) {
      console.error('❌ [GuideStore] 加载用户偏好失败:', error)
    }
  }

  const saveUserPreferences = () => {
    try {
      localStorage.setItem('user-guide-preferences', JSON.stringify(userPreferences.value))
      console.log('💾 [GuideStore] 用户偏好已保存')
    } catch (error) {
      console.error('❌ [GuideStore] 保存用户偏好失败:', error)
    }
  }

  const updatePreference = (key, value) => {
    userPreferences.value[key] = value
    saveUserPreferences()
    console.log(`⚙️ [GuideStore] 更新偏好 ${key}:`, value)
  }

  const checkShouldShowGuide = () => {
    // 检查是否应该显示引导
    const completed = localStorage.getItem('user-guide-completed')
    const skipped = localStorage.getItem('user-guide-skipped')
    
    if (completed || skipped) {
      guideCompleted.value = true
      return false
    }
    
    return userPreferences.value.autoStartGuide
  }

  const getGuideStats = () => {
    // 获取引导统计信息
    return {
      isFirstTime: isFirstTime.value,
      completed: guideCompleted.value,
      currentStep: currentStep.value + 1,
      totalSteps: totalSteps.value,
      progress: progress.value,
      completedDate: localStorage.getItem('user-guide-completed-date'),
      skipped: localStorage.getItem('user-guide-skipped') === 'true'
    }
  }

  // 初始化
  const initialize = () => {
    loadUserPreferences()
    
    // 检查完成状态
    const completed = localStorage.getItem('user-guide-completed')
    if (completed) {
      guideCompleted.value = true
    }
    
    console.log('🚀 [GuideStore] 引导状态管理初始化完成')
  }

  // 自动初始化
  initialize()

  return {
    // 状态
    isGuideActive,
    currentStep,
    guideCompleted,
    userPreferences,
    guideSteps,
    
    // 计算属性
    totalSteps,
    progress,
    currentStepData,
    isFirstTime,
    
    // 方法
    startGuide,
    nextStep,
    previousStep,
    goToStep,
    completeGuide,
    skipGuide,
    resetGuide,
    updatePreference,
    checkShouldShowGuide,
    getGuideStats,
    initialize
  }
})
